/**
 * $Id$
 *
 * Unpublished Work Copyright 2013 Confirmit, Inc. All Rights Reserved.
 *
 * Last changed by $Author$
 * Last changed at $Date$
 */
package com.youtills.core.app.dev;

import com.youtills.core.app.common.ISiteLayout;
import com.youtills.core.app.common.SiteLayout;
import com.youtills.core.lang.StringUtil;
import com.youtills.core.web.IRequestHandler;

/**
 * TODO
 *
 * @author Ravi Kumar Chiluveru (ravic)
 * @since 12.2, (7/11/13 12:33 PM)
 */
public class HexRequestHandler  extends SiteLayout implements IRequestHandler, ISiteLayout {

    public String getMainContentPage() {
        return "/WEB-INF/jsp/dev/hex.jsp";
    }

    private static final String DEFAULT_CHARSET_NAME = "UTF-8";
    private String charsetName;

    public String getCharsetName() {
        if(charsetName == null){
            String param = getContextBean().getRequest().getParameter("charsetName");
            if(param != null){
                param = param.trim();
            }
            charsetName = StringUtil.firstNonEmpty(param, DEFAULT_CHARSET_NAME);
        }
        return charsetName;
    }

    public String getSrc(){
        return getContextBean().getRequest().getParameter("src");
    }

    public String getResult(){
        String result = "";

        String action = getContextBean().getRequest().getParameter("action");
        String src = getContextBean().getRequest().getParameter("src");

        if(!StringUtil.isEmpty(src)){
            try{
                if("Hex".equals(action)){
                    result = toHexString(src.getBytes(getCharsetName()));
                }else if ("Text".equals(action)){
                    result = new String(fromHexString(src), getCharsetName());
                }
            }catch (Exception e){
                result = "Exception: " + e.getMessage();
            }
        }
        return result;
    }

    public static String toHexString(byte[] fieldData) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fieldData.length; i++) {
            int v = (fieldData[i] & 0xFF);
            if (v <= 0xF) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString();
    }

    public static byte[] fromHexString(String s) {
        int length = s.length() / 2;
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            bytes[i] = (byte) ((Character.digit(s.charAt(i * 2), 16) << 4) | Character
                    .digit(s.charAt((i * 2) + 1), 16));
        }
        return bytes;
    }

}